<?php
namespace App\DBs;

use App\DBs\BaseDB;
use Illuminate\Support\Facades\DB;

class AppVersionDB extends BaseDB
{
    /**
     * BUG
     * version 版本号
     * link 下载地址
     * total 下载量
     */

    protected $table = 'app_version';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 列表
     */
    public function getIndex()
    {
        $models = DB::table($this->table)
            ->orderBy('version','desc')
            ->get();
        if (!count($models)) {
            return array('code'=>1, 'msg'=>'没有数据');
        }
        $dataArr = array();
        foreach ($models as $model) {
            $dataArr[] = [
                'version' => $model->version,
                'downloads' => $model->total,
                'link' => $model->link,
            ];
        }
        return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
    }

    /**
     * 详情
     */
    public function getNewOne()
    {
        $model = DB::table($this->table)
            ->orderBy('version','desc')
            ->first();
        $version = 0;
        $total = 0;
        $link = '';
        if ($model) {
            $version = $model->version;
            $total = $model->total;
            $link = $model->link;
        }
        $dataArr = array(
            'version' => $version,
            'downloads' => $total,
            'link' => $link,
        );
        return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
    }

    /**
     * 新增
     */
    public function setAdd($admin,$alm,$genre,$name,$link,$detail)
    {
        //开启事务
        DB::beginTransaction();
        try {
            $lastId = DB::table($this->table)->insertGetId([
                'name' => $name,
                'link' => $link,
                'detail' => $detail,
                'admin' => $admin,
                'alm' => $alm,
                'genre' => $genre,
                'created_at' => time(),
            ]);
            $dataArr = array(
                'proId' => $lastId,
            );
            //提交事务
            DB::commit();
            return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>-1, 'msg'=>'操作失败：'.$e);
        }
    }
}